import axios from "axios";
const isPro = import.meta.env.MODE === "production";

const instance = axios.create({
  baseURL: isPro
    ? import.meta.env.VITE_BASE_API
    : import.meta.env.VITE_BASE_URL,
  timeout: 20 * 1000,
});

// 请求拦截
instance.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    // console.log(error);
    return Promise.reject(error);
  }
);
// 响应拦截
instance.interceptors.response.use(
  (response) => {
    // console.log(response);
    // 状态码
    const code = response.data.code || 200;
    // 返回的信息
    const { msg } = response.data;
    // 二进制数据则直接返回
    if (
      response.request.responseType === "blob" ||
      response.request.responseType === "arraybuffer"
    ) {
      return response;
    }
    if (code === 200) {
      return response.data;
    } else {
      ElMessage({
        message: msg,
        type: "error",
      });
      return Promise.reject(response.data);
    }
  },
  (error) => {
    console.log("err" + error);
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substring(message.length - 3) + "异常";
    }
    ElMessage({
      message: message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default instance;
